/**
 * @description Dashboard Component
 */

import React, { Component } from 'react'
import Sortable from 'sortablejs'
import { Card, Spin } from 'antd'
import { FormattedMessage } from 'react-intl'
import Api from '@api'

const { Meta } = Card

export default class Dashboard extends Component {
  constructor(props) {
    super(props)
    this.state = {
      collapsed: false,
      openKeys: [],
      dashboardList: [],
      isLoading: false,
      // Cancel all subscriptions and asynchronous tasks Flag
      isMounted: false
    }
    this.dragTargetRef = React.createRef()
  }
  componentDidMount() {
    this.setState({
      isMounted: true,
      isLoading: true,
      loadingTip: <FormattedMessage id="i18n_common_loading" />
    })
    // Get data
    Api.get('dashboard', {}, true).then(
      res => {
        if (!this.isMounted && res) {
          this.setState({
            dashboardList: res,
            isLoading: false,
            loadingTip: ''
          })
        }
      },
      () => {
        this.setState({ isLoading: false, loadingTip: '' })
      }
    )
    // Config sortable
    Sortable.create(this.dragTargetRef.current, {
      handle: '.drag-pos',
      animation: 150,
      ghostClass: 'cusor-grabbing', // Class name for the drop placeholder
      chosenClass: 'cusor-grab', // Class name for the chosen item
      dragClass: 'cusor-grabbing', // Class name for the dragging item
      scroll: true,
      setData: function(dataTransfer) {
        dataTransfer.setData('ri-drag-dashboard', '')
      },
      onEnd: function() {
        // TODO: Memory storage function
      }
    })
  }
  componentWillUnmount() {
    // Cancel all subscriptions and asynchronous tasks
    this.setState({ isMounted: false })
  }
  render() {
    return (
      <div
        className="d-flex flex-wrap justify-content-around h-100 overflow-y-auto"
        ref={this.dragTargetRef}
      >
        {this.state.dashboardList.map(item => (
          <Card
            hoverable
            key={item.title}
            cover={
              <img
                alt={item.alt}
                src={item.src}
                className="drag-pos cusor-move"
              />
            }
            className="dashboard-item mt-2"
          >
            <Meta title={item.title} description={item.description} />
          </Card>
        ))}

        <Spin
          tip={this.state.loadingTip}
          spinning={this.state.isLoading}
          className="align-self-center"
          size="large"
        />
      </div>
    )
  }
}
